package com.xlh.controller.courseTest;

import com.xlh.aop.OperationRecording;
import com.xlh.common.Result;
import com.xlh.dto.courseTest.AnswerSheetTypeDTO;
import com.xlh.dto.courseTest.practice.*;
import com.xlh.enums.courseTest.PracticeSaveEnum;
import com.xlh.enums.user.EventCodeEnum;
import com.xlh.exception.common.GlobalException;
import com.xlh.security.UserInfoHolder;
import com.xlh.service.courseTest.PracticeService;
import com.xlh.support.doccheck.service.impl.DocCheckServiceImpl;
import com.xlh.util.FileUtil;
import com.xlh.vo.CascaderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zhr 2019/4/1
 */
@RestController
@Api(tags = "PracticeController", description = "随堂练习")
@RequestMapping("/course/{courseId}/chapter/{chapterId}/practice")
public class PracticeController {
    @Autowired
    private PracticeService practiceService;
    @Autowired
    private UserInfoHolder userInfoHolder;
    @Autowired
    private DocCheckServiceImpl docCheckService;

    @ApiOperation("是否已经提交随堂练习")
    @GetMapping("/status")
    @PreAuthorize("@permissionValidator.isStudent()")
    public Result<Boolean> isSubmitted(@PathVariable Long chapterId, @PathVariable Long courseId) {
        return Result.success(practiceService.isSubmitted(chapterId, userInfoHolder.getUserId(), courseId));
    }

    @ApiOperation("进入随堂练习")
    @GetMapping("")
    @PreAuthorize("@permissionValidator.isTeacherOrStudent()")
    @OperationRecording(codeEnum = EventCodeEnum.CHAPTER_RECORDING, objId = "#{chapterId}", type = "4")
    public Result<PracticeDTO> startPractice(
            @PathVariable("chapterId") Long chapterId,
            @PathVariable Long courseId,
            @RequestParam(value = "questionId", required = false) Long questionId
    ) {
        return Result.success(practiceService.getPractice(chapterId, questionId, userInfoHolder.getUserId(), userInfoHolder.isTeacher(), courseId));
    }
    @ApiOperation("错题练习")
    @PostMapping("/wrongPractice")
    @PreAuthorize("@permissionValidator.isStudent()")
    @OperationRecording(codeEnum = EventCodeEnum.CHAPTER_RECORDING, objId = "#{chapterId}", type = "4")
    public Result<PracticeDTO> wrongPractice(@RequestBody List<Long> questionIds, @RequestParam Long questionId,
                                             @PathVariable("chapterId") Long chapterId,
                                             @PathVariable Long courseId
    ) {
        return Result.success(practiceService.getPracticeOther(chapterId, questionId, questionIds, userInfoHolder.isTeacher(), courseId));
    }
    @ApiOperation("提交随堂练习")
    @PostMapping("/{type}")
    @PreAuthorize("@permissionValidator.isStudent()")
    public Result submitPractice(
            @PathVariable Integer type,
            @PathVariable Long chapterId,
            @PathVariable Long courseId,
            @RequestBody List<AnswerSheetTypeDTO> answerSheetTypeList
    ) {
        switch (PracticeSaveEnum.forType(type)) {
            case SAVE:
                practiceService.savePractice(chapterId, answerSheetTypeList, userInfoHolder.getUserId(), courseId);
                break;
            case SUBMIT:
                practiceService.submitPractice(chapterId, answerSheetTypeList, userInfoHolder.getUserId(), courseId);
                break;
            default:
                throw new GlobalException("参数不合法");
        }
        return Result.success();
    }
    @ApiOperation("上传附件文件")
    @PostMapping("/upload")
    @PreAuthorize("@permissionValidator.isStudent()")
    public Result upload(
            @PathVariable Long chapterId,
            @PathVariable Long courseId, MultipartFile file, @RequestParam Long id) {
        docCheckService.uploadFileOther(userInfoHolder.getUser().getUserNumber(),file,courseId,chapterId,id);
        return Result.success();
    }
    @ApiOperation("查看文件")
    @GetMapping("/view")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<CascaderVO>> viewFile(@PathVariable Long chapterId,
                                             @PathVariable Long courseId, @RequestParam String userNumber, @RequestParam String fileName, @RequestParam Long id) {
        List<CascaderVO> fileTree = docCheckService.viewFileOther(userNumber,courseId,chapterId,id);
        return Result.success(fileTree);
    }
    @ApiOperation("下载文件")
    @GetMapping("/downFile")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<String> downFile(@PathVariable Long chapterId,
                                   @PathVariable Long courseId,
                                   @RequestParam String userNumber,
                                   @RequestParam String fileName,
                                   @RequestParam Long id,
                                   HttpServletResponse response) {
        String filePath = docCheckService.downFile(userNumber,courseId,chapterId,fileName,id);

        try {
            FileUtil.downloadFile(response, filePath, fileName);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @ApiOperation("读取文件")
    @GetMapping("/read")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<String>> read(@RequestParam String path, @PathVariable Long chapterId,
                                     @PathVariable Long courseId, @RequestParam String userNumber, @RequestParam Long id) {

        String basePath = docCheckService.getBasePath(courseId, chapterId, id, userNumber);
        String filePath = basePath + path;
        List<String> fileTree = FileUtil.readLogByList(filePath);
        return Result.success(fileTree);
    }

    @ApiOperation("随堂练习章节统计")
    @GetMapping("/chapterStatistics")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result chapterStatistics(@RequestParam(required = true) Long chapterId,
                                    @RequestParam(required = true) Long classId){

        PracticeChapterDTO practiceChapterDTO = practiceService.chapterStatistics(chapterId, classId);
        return Result.success(practiceChapterDTO);
    }

    @ApiOperation("随堂练习试题正确率统计")
    @GetMapping("/accuracyStatistics")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result accuracyStatistics(@PathVariable("chapterId") Long chapterId,
                                     @RequestParam(required = true) Long classId){
        PracticeAccuracyTypeWrapDTO  result = practiceService.accuracyStatistics(chapterId, classId);

        return Result.success(result);
    }


}
